<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coupon\Coupon;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

/**
 * 优惠卷后台
 * Class CouponController
 * @package App\Http\Controllers\Admin
 */
class CouponController extends Controller
{
    /**
     * 优惠卷列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $coupon = Coupon::orderBy('id', 'desc')->paginate(10);
        $data['list'] = $coupon;
        $data['params'] = $request->all();
        return view('admin.coupon.index', $data);
    }


    /**
     * 优惠卷修改
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        $id = $request->input('id');
        $data['coupon'] = Coupon::find($id);
        return view('admin.coupon.add', $data);
    }


    /**
     * 保存优惠卷
     * @param Request $request
     */
    public function save(Request $request)
    {
        $id = $request->input('id');
        $coupon = Coupon::find($id) ?: new Coupon;

        $fields = ['name', 'max_value', 'start_at', 'end_at', 'per_user_num', 'goods_id', 'scope_type', 'item_valid_begin_at', 'item_valid_time'];
        foreach ($fields as $field) {
            if ($request->has($field)) {
                $coupon->$field = $request->input($field);
            }
        }

        $ret = $coupon->save();
        if ($ret) {
            echo "<meta http-equiv=\"refresh\" content=\"2; url='http://ga.cloudxt.cn/admin_1427a/coupon'\">保存成功";
        } else {
            echo "保存失败";
        }
    }
}